package com.qimu.saiyou.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.qimu.saiyou.annotation.AuthCheck;
import com.qimu.saiyou.common.BaseResponse;
import com.qimu.saiyou.common.DeleteRequest;
import com.qimu.saiyou.common.ErrorCode;
import com.qimu.saiyou.common.ResultUtils;
import com.qimu.saiyou.exception.BusinessException;
import com.qimu.saiyou.exception.ThrowUtils;
import com.qimu.saiyou.manager.RedisLimiterManager;
import com.qimu.saiyou.model.dto.question.QuestionDTO;
import com.qimu.saiyou.model.dto.questionbank.QuestionBankAddRequest;
import com.qimu.saiyou.model.dto.questionbank.QuestionBankQueryRequest;
import com.qimu.saiyou.model.dto.questionbank.QuestionBankQuestionQueryRequest;
import com.qimu.saiyou.model.dto.questionbank.QuestionBankUpdateRequest;
import com.qimu.saiyou.model.entity.Question;
import com.qimu.saiyou.model.entity.QuestionBank;
import com.qimu.saiyou.model.entity.QuestionBankRef;
import com.qimu.saiyou.model.vo.QuestionBankVo;
import com.qimu.saiyou.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 试题题库
 *
 *@author: FeiXiang
 *
 */
@RestController
@RequestMapping("/question_bank")
@Slf4j
public class QuestionBankController {
    @Resource
    private QuestionBankRefService questionBankRefService;

    @Resource
    private QuestionBankService questionBankService;
    @Resource
    private QuestionService questionService;
    @Resource
    private QuestionAnswerService questionAnswerService;
    @Resource
    private UserService userService;
    @Resource
    private RedisLimiterManager redisLimiterManager;

    // region 增删改查

    /**
     * 创建
     *
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(anyRole = {"admin", "teacher"})
    public BaseResponse<Long> addQuestionBank(@RequestBody QuestionBankAddRequest questionBankAddRequest, HttpServletRequest request) {
        if (questionBankAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionBank questionBank = new QuestionBank();
        BeanUtils.copyProperties(questionBankAddRequest, questionBank);
        questionBankService.validQuestionBank(questionBank, true);
        boolean result = questionBankService.save(questionBank);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newQuestionBankId = questionBank.getId();
        return ResultUtils.success(newQuestionBankId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(anyRole = {"admin", "teacher"})
    public BaseResponse<Boolean> deleteQuestionBank(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        QuestionBank oldQuestionBank = questionBankService.getById(id);
        ThrowUtils.throwIf(oldQuestionBank == null, ErrorCode.NOT_FOUND_ERROR);
        boolean b = questionBankService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(anyRole = {"admin", "teacher"})
    public BaseResponse<Boolean> updateQuestionBank(@RequestBody QuestionBankUpdateRequest questionBankUpdateRequest) {
        if (questionBankUpdateRequest == null || questionBankUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionBank questionBank = new QuestionBank();
        BeanUtils.copyProperties(questionBankUpdateRequest, questionBank);
        // 参数校验
        questionBankService.validQuestionBank(questionBank, false);
        long id = questionBank.getId();
        // 判断是否存在
        QuestionBank oldQuestionBank = questionBankService.getById(id);
        ThrowUtils.throwIf(oldQuestionBank == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = questionBankService.updateById(questionBank);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionBankVo> getQuestionBankVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionBank questionBank = questionBankService.getById(id);
        if (questionBank == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        QuestionBankVo questionBankVo = questionBankService.getQuestionBankVo(questionBank, request);
        return ResultUtils.success(questionBankVo);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param questionBankQueryRequest
     * @return
     */
    @PostMapping("/get/list/page")
    public BaseResponse<QuestionBankVo> listQuestionBankAndQuestionById(@RequestBody QuestionBankQuestionQueryRequest questionBankQueryRequest, HttpServletRequest request) {
        if (questionBankQueryRequest == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        long current = questionBankQueryRequest.getCurrent();
        long size = questionBankQueryRequest.getPageSize();
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        QuestionBankVo questionBankVo = new QuestionBankVo();
        // 关联查询
        MPJLambdaWrapper<Question> wrapper = new MPJLambdaWrapper<Question>()
                .selectAll(Question.class)
                .select(QuestionBankRef::getQuestionBankId)
                .eq(ObjectUtils.isNotEmpty(questionBankQueryRequest.getId()), QuestionBankRef::getQuestionBankId, questionBankQueryRequest.getId())
                .eq(ObjectUtils.isNotEmpty(questionBankQueryRequest.getType()), Question::getType, questionBankQueryRequest.getType())
                .like(StringUtils.isNotBlank(questionBankQueryRequest.getSearchText()), Question::getContent, questionBankQueryRequest.getSearchText())
                .leftJoin(QuestionBankRef.class, QuestionBankRef::getQuestionId, Question::getId);
        Page<QuestionDTO> questionDTOPage = questionService.selectJoinListPage(new Page<>(current, size), QuestionDTO.class, wrapper);
        questionBankVo.setQuestionList(questionService.getQuestionVOPageByDTO(questionDTOPage).getRecords());
        questionBankVo.setCurrent(questionDTOPage.getCurrent());
        questionBankVo.setSize(questionDTOPage.getSize());
        questionBankVo.setTotal(questionDTOPage.getTotal());
        return ResultUtils.success(questionBankVo);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param questionBankQueryRequest
     * @return
     */
    @PostMapping("/list/page/question_bank")
    public BaseResponse<Page<QuestionBank>> listQuestionBank(@RequestBody QuestionBankQueryRequest questionBankQueryRequest, HttpServletRequest request) {
        if (questionBankQueryRequest == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        long current = questionBankQueryRequest.getCurrent();
        long size = questionBankQueryRequest.getPageSize();

        Page<QuestionBank> questionBankPage = questionBankService.page(new Page<>(current, size),
                questionBankService.getQueryWrapper(questionBankQueryRequest));
        return ResultUtils.success(questionBankPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param questionBankQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionBankVo>> listQuestionBankVOByPage(@RequestBody QuestionBankQueryRequest questionBankQueryRequest,
                                                                       HttpServletRequest request) {
        long current = questionBankQueryRequest.getCurrent();
        long size = questionBankQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<QuestionBank> questionBankPage = questionBankService.page(new Page<>(current, size),
                questionBankService.getQueryWrapper(questionBankQueryRequest));
        return ResultUtils.success(questionBankService.getQuestionBankVoPage(questionBankPage, request));
    }

    // endregion


}
